﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedLib.MessageFramework;
using Tracy.DataModel;
using TracyGUI.View;
using SharedLib.MessageFramework.Messages;

namespace TracyGUI.Controller.EntryTabs
{
    class SearchResultTabPageViewController : EntryTabPageViewControllerBase
    {
        private string _keyword;

        public string Keyword
        {
            get { return _keyword; }
            set { 
                _keyword = value;
                Refresh();
            }
        }



        AsyncActionAppMessage _lastSearchMsg = null;
        private void Refresh()
        {
            View.Name = "search";
            View.Text = String.Format(Tracy.TracyFacade.Instance.LanguageManager.GetText("EntryTabSearchResultLoading"), Keyword);
            if (_lastSearchMsg != null) _lastSearchMsg.CancelFlag = true; //Cancel last search
            _lastSearchMsg = new AsyncActionAppMessage(this, msg =>
            {
                Tracy.TracyFacade.Instance.SearchEngine.Search(Keyword);
                if (!msg.CancelFlag)
                {
                    View.Text = String.Format(Tracy.TracyFacade.Instance.LanguageManager.GetText("EntryTabSearchResult"), Keyword);
                    FileTabPage.LoadMediaFiles(Tracy.TracyFacade.Instance.SearchEngine.FileSearchResult, () => msg.CancelFlag);
                    ResTabPage.LoadResources(Tracy.TracyFacade.Instance.SearchEngine.ResourceSearchResult, () => msg.CancelFlag);
                }
            }, "AsyncActionAppMessage_Search");
            _lastSearchMsg.Priority = MessagePriority.High;
            Console.WriteLine("[" + System.DateTime.Now.ToString("HH:mm:ss fff") + "] Search Message Enqueued: " + Keyword);
            Tracy.TracyFacade.Instance.MessageDispatcher.EnqueueMessage(_lastSearchMsg);
        }

        public SearchResultTabPageViewController(string keyword) : base()
        {
            Keyword = keyword;
        }

        public SearchResultTabPageViewController()
            : base()
        {
        }

        #region ViewState
        public override void LoadViewState(Model.ViewStateManager manager, System.Xml.XmlElement viewStateNode)
        {
            base.LoadViewState(manager, viewStateNode);
            Keyword = viewStateNode.GetAttribute("search-keyword");
        }

        public override void SaveViewState(Model.ViewStateManager manager, System.Xml.XmlElement viewStateNode, System.Xml.XmlDocument doc)
        {
            viewStateNode.SetAttribute("search-keyword", Keyword);
            base.SaveViewState(manager, viewStateNode, doc);
        }
        #endregion
    }
}
